/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.mobao.marshal;

import com.acooly.core.utils.Encodes;
import com.acooly.core.utils.Exceptions;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiMarshal;
import com.acooly.module.openapi.client.api.marshal.ApiMarshalSupport;
import com.acooly.module.openapi.client.api.util.XStreams;
import com.acooly.module.openapi.client.provider.mobao.domain.MoBaoRequest;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhangpu
 */
public class MoBaoRedirectMarshal extends ApiMarshalSupport implements ApiMarshal<String, MoBaoRequest> {
    private static Logger logger = LoggerFactory.getLogger(MoBaoRedirectMarshal.class);
    protected static KeyStoreInfo keystore = new KeyStoreInfo();

    @SuppressWarnings("unchecked")
    @Override
    public String marshal(MoBaoRequest source) {
        try {
            String plain = XStreams.toXmlCompact(source);
            logger.info("跳转报文 明文:{}", plain);
            String signature = getSigner(SignTypeEnum.Cert).sign(getMessage(plain), keystore);
            String cipher = getGetMessage(plain, signature);
            logger.info("跳转报文 密文:{}", cipher);
            return cipher;
        } catch (Exception e) {
            throw new ApiClientException("跳转报文 错误:" + e.getMessage());
        }
    }

    protected String getMessage(String message) {
        try {
            return Encodes.encodeBase64(message.getBytes("UTF-8"));
        } catch (Exception e) {
            throw Exceptions.unchecked(e);
        }
    }

    protected String getGetMessage(String message, String signature) {
        StringBuffer sb = new StringBuffer();
        sb.append("message=");
        sb.append(Encodes.urlEncode(getMessage(message)));
        sb.append("&");
        sb.append("signature=");
        sb.append(signature);
        return sb.toString();
    }

}
